import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  DragDropContext,
  Droppable,
  DropResult,
  DroppableProvided,
} from 'react-beautiful-dnd';
import DragColumn from './components/DragColumn';
import {
  dropDragActionAsync,
  dragColumn,
  dragRowSame,
  dragRowDiff,
} from 'store/actions/drop-drag';
import { RootState } from 'store';
import style from './index.module.scss';

const DropDrag: React.FC = () => {
  const dispatch = useDispatch();
  const { columnIds, columns } = useSelector(
    (state: RootState) => state.dropDrag
  );
  useEffect(() => {
    dispatch(dropDragActionAsync());
  }, [dispatch]);

  const onDragEnd = (result: DropResult) => {
    const { source, destination, draggableId, type } = result;
    if (!destination) {
      return;
    }

    if (
      source.index === destination.index &&
      source.droppableId === destination.droppableId
    ) {
      return;
    }

    if (type === 'column') {
      const tempColumnIds = [...columnIds];
      tempColumnIds.splice(source.index, 1);
      tempColumnIds.splice(destination.index, 0, draggableId);

      dispatch(dragColumn(tempColumnIds));

      return;
    }

    const startId = source.droppableId;
    const endId = destination.droppableId;

    if (startId === endId) {
      // 在同一列
      const tempRowIds = [...(columns[startId]?.rowIds || [])];
      tempRowIds.splice(source.index, 1);
      tempRowIds.splice(destination.index, 0, draggableId);

      dispatch(dragRowSame({ columnId: startId, rowIds: tempRowIds }));
    } else {
      // 在不同列
      const tempStartRowIds = [...(columns[startId]?.rowIds || [])];
      tempStartRowIds.splice(source.index, 1);
      const tempEndRowIds = [...(columns[endId]?.rowIds || [])];
      tempEndRowIds.splice(destination.index, 0, draggableId);

      dispatch(
        dragRowDiff({
          columnId: [startId, endId],
          rowIds: [tempStartRowIds, tempEndRowIds],
        })
      );
    }
  };

  return (
    <div className={style.root}>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable
          droppableId="drop-column"
          direction="horizontal"
          type="column"
        >
          {(provided: DroppableProvided) => {
            return (
              <div
                {...provided.droppableProps}
                ref={provided.innerRef}
                className="drop-column"
              >
                {columnIds?.map((id, index) => {
                  return (
                    <DragColumn
                      key={id}
                      index={index}
                      columnId={id}
                    ></DragColumn>
                  );
                })}
                {provided.placeholder}
              </div>
            );
          }}
        </Droppable>
      </DragDropContext>
    </div>
  );
};
DropDrag.displayName = 'DropDrag';
export default DropDrag;
